package com.ttg.controller;

//~--- non-JDK imports --------------------------------------------------------

import com.ttg.contants.TestContants;
import com.ttg.contants.UrlContants;
import com.ttg.pojo.BatchProfitPojo;
import com.ttg.pojo.SyncInfoDTO;
import com.ttg.security.EncryptionUtils;
import com.ttg.service.BatchProfitService;
import com.ttg.utils.Bytes;
import com.ttg.utils.DateUtil;
import com.ttg.utils.IdGenerator;
import com.ttg.utils.connection.TTGHttpClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

//~--- classes ----------------------------------------------------------------

/**
 * Class BatchProfitController
 * Description 代付接口调用DEMO
 * Create 2016-06-23 17:29:29
 * @author Ardy
 */
@Controller
@RequestMapping("/batch_profit")
public class BatchProfitDemoController {

    /**
     * Field logger
     * Description
     */
    private static final Logger logger = LoggerFactory.getLogger(BatchProfitDemoController.class);
@Autowired
    private BatchProfitService batchProfitService;
    /**
     * Method testBatchProfit
     * Description 说明：
     *
     * @param model 说明：
     *
     * @return 返回值说明：
     */
    @RequestMapping
    public String testBatchProfit(Model model) {

        // 准备页面提交的数据
        BatchProfitPojo batchProfitPojo = new BatchProfitPojo();
        batchProfitPojo.setMerchantId(TestContants.MERCHANT_ID);
        batchProfitPojo.setAppId(TestContants.APP_ID);
        batchProfitPojo.setBatchNo(IdGenerator.genOrdId16());
        batchProfitPojo.setCountRecord(2);
        batchProfitPojo.setTotalAmount(2D);
        model.addAttribute("batchProfit",batchProfitPojo);
        return "demo/batch_profit_demo";
    }



    @RequestMapping(value = "/do_batch_profit",method = RequestMethod.POST )
    @ResponseBody
    public SyncInfoDTO doBatchProfit(BatchProfitPojo batchProfitPojo, @RequestParam(value = "uploadFile") MultipartFile uploadFile){
        logger.debug("batch profit :{}",batchProfitPojo);
        String      filePath    = UrlContants.UPLOAD_URL
                + DateUtil.date2Str(new Date(), DateUtil.dtShort) + File.separator + batchProfitPojo.getMerchantId()
                + File.separator + batchProfitPojo.getBatchNo() + File.separator;
        SyncInfoDTO syncInfoDTO = null;
        try {
            String fileName = DateUtil.date2Str(new Date(), DateUtil.dtLong) + "_" + uploadFile.getOriginalFilename();
            File dir      = new File(filePath);
            logger.debug("filePath : {}",filePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File tmpFile = new File(filePath + fileName);

            uploadFile.transferTo(tmpFile);

            batchProfitPojo.setSignatureAlgorithm(TestContants.SIGNATUREALGORITHM);
            batchProfitPojo.attachFile(tmpFile,"file");
            batchProfitPojo.setFileDigest(Bytes.getFileMD5Base64(tmpFile, TestContants.CHARSET_UTF8));
            batchProfitPojo.setSignatureInfo(EncryptionUtils.encryption(batchProfitPojo.getAllParameters()));

            logger.debug("batch profit :{}",batchProfitPojo);

            logger.debug("batch :{}" ,batchProfitPojo.getAllParameters());
            syncInfoDTO = batchProfitService.testBatchProfit(UrlContants.BATCH_PROFIT_URL,  batchProfitPojo );
            logger.debug("resp :{}",syncInfoDTO);
        } catch (IOException | TTGHttpClientException e) {
            syncInfoDTO = new SyncInfoDTO();
            syncInfoDTO.setMessage(e.getMessage());
            logger.error("Exception:{}", e.fillInStackTrace());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //response.setHeader("Access-Control-Allow-Origin", "*");
        return  syncInfoDTO;
    }

}


//~ Formatted by Jindent --- http://www.jindent.com
